package com.ruoyi.merchant.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.merchant.domain.BaseDeviceInfo;
import com.ruoyi.merchant.domain.Province;
import com.ruoyi.merchant.dto.BaseDeviceInfoDto;
import com.ruoyi.merchant.service.IBaseDeviceInfoService;
import com.ruoyi.merchant.service.IProvinceService;
import com.ruoyi.merchant.util.H002ModelCmdEnum;
import com.ruoyi.merchant.util.MyStringUtils;
import com.ruoyi.merchant.vo.CustomerBaseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.merchant.mapper.CustomerBaseMapper;
import com.ruoyi.merchant.domain.CustomerBase;
import com.ruoyi.merchant.service.ICustomerBaseService;

/**
 * 客户基本信息Service业务层处理
 * 
 * @author chengxin.ju
 * @date 2023-12-12
 */
@Slf4j
@Service
public class CustomerBaseServiceImpl implements ICustomerBaseService 
{
    @Autowired
    private CustomerBaseMapper customerBaseMapper;

    /**
     * 查询客户基本信息
     * 
     * @param ID 客户基本信息主键
     * @return 客户基本信息
     */
    @Override
    public CustomerBase selectCustomerBaseByID(String ID)
    {
        return customerBaseMapper.selectCustomerBaseByID(ID);
    }

    /**
     * 查询客户基本信息列表
     *
     * @param customerBase 客户基本信息
     * @return 客户基本信息
     */
    @Override
    public List<CustomerBaseVo> selectCustomerBaseList(CustomerBase customerBase)
    {
        return customerBaseMapper.selectCustomerBaseList(customerBase);
    }

    @Autowired
    private IBaseDeviceInfoService baseDeviceInfoService;

    /**
     * 新增客户基本信息
     *
     * @param customerBase 客户基本信息
     * @return 结果
     */
    @Override
    public CustomerBase insertCustomerBase(CustomerBase customerBase) throws Exception {
        String username = SecurityUtils.getUsername();
        customerBase.setId(IdUtils.fastSimpleUUID());
        customerBase.setCreatedTime(new Date());
        customerBase.setCreateBy(username);
        if (customerBase.getCustomerAddressProvince()  != null){
            String customerNum = getCustomerNum(customerBase.getCustomerAddressProvince());
            customerBase.setCustomerNum(customerNum);
        }else {
            throw new ServiceException("省份编码不能为空");
        }
        customerBaseMapper.insertCustomerBase(customerBase);
        return customerBase;
    }


    @Autowired
    IProvinceService provinceService;

    /**
     * 生成客户编码
     *
     * @param provinceId
     * @return String
     * @author zhaocaisen
     * @since 2020-06-20
     */
    private String getCustomerNum(Long provinceId) {
        String str = "";
        Province p = provinceService.selectProvinceById(provinceId);
        if (p == null) {
            log.error("生成客户编码失败，获取省编码失败");
        } else {
            String province = p.getAbbreviation();
            str = "KU" + province;
            int count = getCountForProvince(str);
            str = str + (MyStringUtils.formatStr(String.valueOf(count + 1), 8, "0", "left"));
        }
        return str;
    }


    /**
     * 每个省份等级人数（生成客户编码）
     *
     * @param province
     * @return int
     * @author zhaocaisen
     * @since 2020-06-20
     */
    public int getCountForProvince(String province) {
        return customerBaseMapper.getCountForProvince(province);
    }

    /**
     * 修改客户基本信息
     *
     * @param customerBase 客户基本信息
     * @return 结果
     */
    @Override
    public CustomerBase updateCustomerBase(CustomerBase customerBase) throws Exception {

        CustomerBase customerBase1 = customerBaseMapper.selectCustomerBaseByID(customerBase.getId());
        if (customerBase1 ==null){
            return null;
        }

        if (customerBase.getCustomerAddressProvince() != null &&
                customerBase1.getCustomerAddressProvince() != null &&
                customerBase.getCustomerAddressProvince().longValue() != customerBase1.getCustomerAddressProvince().longValue()){
            String customerNum = getCustomerNum(customerBase.getCustomerAddressProvince());
            customerBase.setCustomerNum(customerNum);
        }
        String username = SecurityUtils.getUsername();
        customerBase.setUpdateTime(new Date());
        customerBase.setUpdatedBy(username);
        customerBaseMapper.updateCustomerBase(customerBase);

        BaseDeviceInfoDto baseDeviceInfo = new BaseDeviceInfoDto();
        baseDeviceInfo.setCustomerId(customerBase1.getId());
        List<BaseDeviceInfo> baseDeviceInfos = baseDeviceInfoService.selectBaseDeviceInfoList(baseDeviceInfo);
        if (CollectionUtils.isNotEmpty(baseDeviceInfos)){
            for (BaseDeviceInfo obj: baseDeviceInfos) {
                BaseDeviceInfoDto baseDeviceInfoDto = new BaseDeviceInfoDto();
                baseDeviceInfoDto.setId(obj.getId());
                baseDeviceInfoDto.setAppUserId(customerBase1.getAppUserId());
                baseDeviceInfoService.updateBaseDeviceInfo(baseDeviceInfoDto);
            }
        }
        return customerBase;
    }

    /**
     * 批量删除客户基本信息
     * 
     * @param IDs 需要删除的客户基本信息主键
     * @return 结果
     */
    @Override
    public int deleteCustomerBaseByIDs(String[] IDs)
    {
        return customerBaseMapper.deleteCustomerBaseByIDs(IDs);
    }

    /**
     * 删除客户基本信息信息
     * 
     * @param ID 客户基本信息主键
     * @return 结果
     */
    @Override
    public int deleteCustomerBaseByID(String ID)
    {
        return customerBaseMapper.deleteCustomerBaseByID(ID);
    }


//    @Override
//    public List<CustomerBaseVo> selectCustomerBaseListV2(CustomerBase customerBase) {
//        return customerBaseMapper.selectCustomerBaseListV2(customerBase);
//    }
}
